import face_model
import argparse
import sqlite3
import os
import json
import cv2
import numpy as np
import face_preprocess

os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT']="0"
# region+ 加载模型
print('start to load model done!')
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.add_argument('--model', default='model/model-r100-ii/model,0', help='path to load model.')
parser.add_argument('--ga-model', default='ga-model/model,0', help='path to load model.')
parser.add_argument('--gpu', default=0, type=int, help='gpu id')
parser.add_argument('--det', default=2, type=int, help='mtcnn option, 1 means using R+O, 0 means detect from begining,2 meanus retinaface-r50')
parser.add_argument('--flip', default=0, type=int, help='whether do lr flip aug')
parser.add_argument('--threshold', default=1.24, type=float, help='ver dist threshold')
args = parser.parse_args()
model = face_model.FaceModel(args)
print('load model done!')
# endregion


def get_feature_face_from_file(img_file):
    img = cv2.imread(img_file)
    box, img = model.get_input(img)
    fea = model.get_feature(img)
    return box, fea


def get_feature_faces_from_file(img_file):
    img = cv2.imread(img_file)
    boxes, imgs = model.get_inputs(img)
    features = []
    for i in range(boxes.shape[0]):
        fea = model.get_feature(imgs[i])
        features.append(fea)
    return boxes, features


def store_feature_to_sqlite():
    conn = sqlite3.connect('test.db')
    c = conn.cursor()
    path = r'static/img/pic0/'
    userIds = c.execute('select Id from sys_user;').fetchall()
    for row in userIds:
        feature_strs = []
        userId = str(row[0])
        filename = userId + '.jpg'
        temppath = os.path.join(path, filename)
        if os.path.exists(temppath):
            box, fea = get_feature_face_from_file(temppath)
            feature_str = json.dumps(fea.tolist())
            c.execute('update sys_user set feature=? where Id=?',
                      (feature_str, userId))
        else:
            feature_str = None
            print('工号为%s的人员照片不存在！'%str(userId))
    conn.commit()



def compare(arrayobj,arrayobj2):
    peoples=[]
    peoples.append(arrayobj2)
    peoples=np.array(peoples)
    # global strangers, strangers_index
    # global person_Ids,recent_Features
    arrayobj = np.array(arrayobj)
    dot = np.dot(arrayobj, peoples.T)
    norm_arrayobj = np.linalg.norm(arrayobj)
    # norm_arraysets = np.array([np.linalg.norm(row) for row in peoples])
    norm_arraysets = np.array(np.linalg.norm(peoples, axis=1))
    cos = dot / (norm_arrayobj * norm_arraysets)
    index = np.argmax(cos)
    # 在数据库中比对成功；
    if cos[index] > 0.4:
        # recent_Features[index] = arrayobj
        return True, index, cos[index]
    else:
        return False, index, cos[index]




if __name__ == '__main__':
    # 初始化数据库中的用户特征数据
    store_feature_to_sqlite()
    # print('初始化完成')

    # params = ['liing',None]
    # conn = sqlite3.connect('test.db')
    # c = conn.cursor()
    # c.execute('insert into test(Id,Name,Name2) values(?,?,?)', (1002, params[0],params[1]))
    # conn.commit()
    #print()
    # path = r'static/img/pic0/'
    # img1=cv2.imread(os.path.join(path,'1001.jpg'))
    # img2=cv2.imread(os.path.join(path,'1002.jpg'))
    # box,aligned=model.get_input(img1)
    # gender,age=model.get_ga(aligned)
    # box1,fea1=get_feature_face_from_file(os.path.join(path,'1007-0.jpg'))
    # box2,fea2=get_feature_face_from_file(os.path.join(path,'1007-1.jpg'))
    # result=compare(fea1,fea2)
    print()




